package com.powernode.rules.service.impl;

import com.powernode.model.form.rules.FeeRuleRequest;
import com.powernode.model.form.rules.FeeRuleRequestForm;
import com.powernode.model.vo.rules.FeeRuleResponse;
import com.powernode.model.vo.rules.FeeRuleResponseVo;
import com.powernode.rules.service.FeeRuleService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

/**
 * 费用规则服务实现类
 * 使用Drools规则引擎计算订单费用
 */
@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class FeeRuleServiceImpl implements FeeRuleService {
    @Resource
    private KieContainer kieContainer; // Drools规则引擎容器

    @Override
    public FeeRuleResponseVo calculateOrderFee(FeeRuleRequestForm feeRuleRequestForm) {
        // 创建费用规则请求对象
        FeeRuleRequest feeRuleRequest = new FeeRuleRequest();
        feeRuleRequest.setWaitMinute(feeRuleRequestForm.getWaitMinute()); // 设置等待时间（分钟）
        feeRuleRequest.setStartTime(new DateTime(feeRuleRequestForm.getStartTime()).toString("HH:mm:ss")); // 格式化开始时间
        feeRuleRequest.setDistance(feeRuleRequestForm.getDistance()); // 设置距离

        // 创建Drools会话
        KieSession kieSession = kieContainer.newKieSession();
        // 创建费用规则响应对象
        FeeRuleResponse feeRuleResponse = new FeeRuleResponse();
        // 设置全局变量，用于规则文件中访问
        kieSession.setGlobal("feeRuleResponse", feeRuleResponse);
        // 插入事实对象到规则引擎
        kieSession.insert(feeRuleRequest);
        // 执行所有匹配的规则
        kieSession.fireAllRules();
        // 释放会话资源
        kieSession.dispose();

        // 创建响应VO对象并复制属性
        FeeRuleResponseVo feeRuleResponseVo = new FeeRuleResponseVo();
        BeanUtils.copyProperties(feeRuleResponse, feeRuleResponseVo);
        return feeRuleResponseVo; // 返回计算结果
    }
}

